<template>
  <div class="chat-box-dialog">
    <div class="chat-box-dialog-header">
      <div class="chat-box-dialog-name">某个人</div>
      <div class="chat-box-dialog-close">
        <i class="el-icon-close"></i>
      </div>
    </div>

    <div class="chat-box-dialog-content" ref="chatScroll">
      <div>
        <!-- <div class="chat-box-dialog-item-time">12:08</div> -->
        <template v-for="(item, idx) in messagelist">
          <div :key="`a-${idx}`" v-if="item.type === 1" class="chat-box-dialog-item-left">
            <div class="chat-box-dialog-item-avatar"></div>
            <div class="chat-box-dialog-item-message">{{item.message}}</div>
          </div>
          <div :key="`b-${idx}`" v-if="item.type === 2" class="chat-box-dialog-item-right">
            <div class="chat-box-dialog-item-message">{{item.message}}</div>
            <div class="chat-box-dialog-item-avatar"></div>
          </div>
        </template>
      </div>
    </div>

    <div class="chat-box-dialog-footer">
      <div class="chat-box-dialog-footer-icons">
        <i class="el-icon-microphone chat-box-dialog-footer-icon" @click="microHandle"></i>
        <i class="el-icon-video-camera chat-box-dialog-footer-icon" @click="cameraHandle"></i>
      </div>
      <div class="chat-box-dialog-footer-input">
        <el-input :rows="4" v-model="message" type="textarea"></el-input>
        <div @click="sendMessage" class="chat-box-dialog-footer-send">发送</div>
      </div>
    </div>

    <div v-if="showMicroBox" class="chat-box-dialog-micro">
      <div>{{showMicroBox}}</div>
      <el-button @click="closeMicro" type="danger">挂断</el-button>
    </div>

    <audio hidden ref="audio" className="room-video" autoPlay></audio>
  </div>
</template>

<script>
import BScroll from '@better-scroll/core';
import { Input, MessageBox, Button } from 'element-ui';
import { initChat } from '../../helper/socket';

export default {
  props: ['user'],
  components: {
    'el-input': Input,
    'el-button': Button,
  },
  data() {
    return {
      messagelist: [],
      message: '',
      showMicroBox: '',
    };
  },
  watch: {
    // eslint-disable-next-line
    'messagelist.length': function() {
      this.$nextTick().then(() => {
        this.scroller.refresh();
        this.scroller.scrollTo(0, this.scroller.maxScrollY);
      });
    },
  },
  mounted() {
    this.scroller = new BScroll(this.$refs.chatScroll);

    initChat().then((io) => {
      io.on('message', async (data) => {
        if (data.kind === 1) {
          this.messagelist.push({ type: 1, message: data.data });
        }

        // 对方想要与你语音通话
        if (data.kind === 2) {
          this.messageConfirm = MessageBox.confirm('有人想要与你进行语音通话').then(async () => {
            const iceServers = [{ urls: [], username: io.id, credential: io.id }];
            this.remoteStream = new MediaStream();

            this.stream = await window.navigator.mediaDevices.getUserMedia({ audio: true, video: false });
            this.connection = new RTCPeerConnection({ iceServers });

            this.stream.getTracks().forEach((track) => {
              if (track.kind === 'audio') {
                this.audioTrack = track;
                this.audioTracker = this.connection.addTrack(track, this.stream);
              }

              if (track.kind === 'video') {
                this.videoTrack = track;
                this.videoTracker = this.connection.addTrack(track, this.stream);
              }
            });

            this.connection.ontrack = (e) => {
              this.remoteStream.addTrack(e.track);
              this.$refs.audio.srcObject = this.remoteStream;
            };

            this.connection.onicecandidate = (e) => {
              if (e.candidate) {
                io.emit('message', {
                  kind: 6,
                  token: window.localStorage.getItem('__token__'),
                  toUserID: data.fromUserID,
                  data: e.candidate,
                });
              }
            };

            this.connection.createOffer().then(async (offer) => {
              await this.connection.setLocalDescription(offer);

              io.emit('message', {
                kind: 4,
                token: window.localStorage.getItem('__token__'),
                toUserID: data.fromUserID,
                data: this.connection.localDescription,
              });
            });

            this.showMicroBox = '通话中...';
          }).catch(() => {
            io.emit('message', {
              token: window.localStorage.getItem('__token__'),
              toUserID: data.fromUserID,
              kind: 3,
            });
          });
        }

        // 对方拒绝了你的语音通话
        if (data.kind === 3) {
          try {
            MessageBox.close();
          // eslint-disable-next-line
          } catch(err) {}

          // eslint-disable-next-line
          if (this.audioTrack) {
            this.audioTrack.stop();
            this.audioTracker.replaceTrack(this.audioTrack);
          }
          // eslint-disable-next-line
          if (this.videoTrack) {
            this.videoTrack.stop();
            this.videoTracker.replaceTrack(this.videoTrack);
          }
          this.showMicroBox = '';
        }

        // 对方同意了你的语音通话
        if (data.kind === 4) {
          this.connection.ontrack = (e) => {
            this.remoteStream.addTrack(e.track);
            this.$refs.audio.srcObject = this.remoteStream;
          };

          this.connection.onicecandidate = (e) => {
            if (e.candidate) {
              io.emit('message', {
                kind: 6,
                token: window.localStorage.getItem('__token__'),
                toUserID: data.fromUserID,
                data: e.candidate,
              });
            }
          };

          this.connection.setRemoteDescription(new RTCSessionDescription(data.data)).then(() => {
            this.connection.createAnswer().then(async (answer) => {
              await this.connection.setLocalDescription(answer);

              io.emit('message', {
                kind: 7,
                token: window.localStorage.getItem('__token__'),
                toUserID: data.fromUserID,
                data: this.connection.localDescription,
              });
            });
          });
          this.showMicroBox = '通话中...';
        }

        // 对方挂断了语音通话
        if (data.kind === 5) {
          this.showMicroBox = '';
        }

        // 互相发送 candidate
        if (data.kind === 6) {
          this.connection.addIceCandidate(new RTCIceCandidate(data.data));
        }

        // 对方收到 offer 并后传了 answer
        if (data.kind === 7) {
          this.connection.setRemoteDescription(new RTCSessionDescription(data.data));
        }
      });
    });
  },
  methods: {
    // 挂断语音通话
    closeMicro() {
      initChat().then(async (io) => {
        // eslint-disable-next-line
        if (this.audioTrack) {
          this.audioTrack.stop();
          this.audioTracker.replaceTrack(this.audioTrack);
        }
        // eslint-disable-next-line
        if (this.videoTrack) {
          this.videoTrack.stop();
          this.videoTracker.replaceTrack(this.videoTrack);
        }

        this.showMicroBox = '';

        io.emit('message', {
          token: window.localStorage.getItem('__token__'),
          toUserID: this.user.friendID,
          kind: 3,
        });
      });
    },
    // 语音通话
    microHandle() {
      initChat().then(async (io) => {
        const iceServers = [{ urls: [], username: io.id, credential: io.id }];
        this.remoteStream = new MediaStream();

        this.stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
        this.connection = new RTCPeerConnection({ iceServers });

        this.stream.getTracks().forEach((track) => {
          if (track.kind === 'audio') {
            this.audioTrack = track;
            this.audioTracker = this.connection.addTrack(track, this.stream);
          }

          if (track.kind === 'video') {
            this.videoTrack = track;
            this.videoTracker = this.connection.addTrack(track, this.stream);
          }
        });

        io.emit('message', {
          token: window.localStorage.getItem('__token__'),
          toUserID: this.user.friendID,
          kind: 2,
        });

        this.showMicroBox = '呼叫中...';
      });
    },
    // 视频通话
    cameraHandle() {},
    sendMessage() {
      initChat().then((io) => {
        io.emit('message', {
          token: window.localStorage.getItem('__token__'),
          toUserID: this.user.friendID,
          kind: 1,
          data: this.message,
        });

        this.messagelist.push({
          type: 2,
          message: this.message,
        });

        this.message = '';
      });
    },
  },
};
</script>

<style>
/*  */
.chat-box-dialog {
  position: fixed;
  padding: 0 15px;
  width: calc(100vw - 320px);
  height: 100vh;
  border-right: 1px solid #e8e8e8;
  border-radius: 0 15px 15px 0;
  box-sizing: border-box;
  background-color: #fff;
  left: 280px;
  top: 0;
  z-index: 1000;
}

/*  */
.chat-box-dialog-header {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  border-bottom: 1px solid #f5f5f5;
}
.chat-box-dialog-name {
  color: #666;
}

/*  */
.chat-box-dialog-content {
  box-sizing: border-box;
  height: calc(100vh - 200px);
  overflow-y: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.chat-box-dialog-item-time {
  display: inline-block;
  height: 24px;
  line-height: 24px;
  border-radius: 12px;
  padding: 0 10px;
  font-size: 12px;
  color: #999;
  background-color: #f5f5f5;
  margin: 10px 0;
  margin-left: 50%;
  transform: translateX(-50%);
}
.chat-box-dialog-item-left {
  margin: 10px 0;
  width: calc(100vw - 350px);
  display: flex;
  justify-content: flex-start;
}

.chat-box-dialog-item-right {
  margin: 10px 0;
  width: calc(100vw - 350px);
  display: flex;
  justify-content: flex-end;
}

.chat-box-dialog-item-avatar {
  width: 30px;
  height: 30px;
  border-radius: 15px;
  background-color: #f5f5f5;
  margin-right: 10px;
}

.chat-box-dialog-item-message {
  width: 500px;
  word-wrap: break-word;
  padding: 10px;
  border-radius: 5px;
  background-color: #f5f5f5;
}

.chat-box-dialog-item-right .chat-box-dialog-item-avatar {
  margin-left: 10px;
}

/*  */
.chat-box-dialog-footer {
  box-sizing: border-box;
  height: 150px;
}

.chat-box-dialog-footer-icons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 30px;
}
.chat-box-dialog-footer-icon {
  font-size: 24px;
  margin: 0 10px;
  cursor: pointer;
}
.chat-box-dialog-footer-input {
  margin-top: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.chat-box-dialog-footer-send {
  width: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #409eff;
  color: #fff;
  font-weight: bold;
  margin-left: 5px;
  height: 96px;
  border-radius: 0 5px 5px 0;
  cursor: pointer;
  user-select: none;
}

.chat-box-dialog-micro {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 5px;
}
</style>
